package com.ysyc.driver_ee.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ysyc.driver_ee.R;
import com.ysyc.driver_ee.base.BaseActivity;
import com.ysyc.driver_ee.manager.TakePictureManager;
import com.ysyc.driver_ee.simplecropview.CropImageView;
import com.ysyc.driver_ee.simplecropview.callback.CropCallback;
import com.ysyc.driver_ee.tools.LogUtils;
import com.ysyc.driver_ee.tools.ScreenUtils;
import com.ysyc.driver_ee.widget.ClipImageView;
import com.ysyc.driver_ee.widget.TitleView;

import java.io.File;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * <p>描述：(这里用一句话描述这个类的作用)</p>
 * 作者： Chan<br>
 * 日期： 2018/11/8 20:32<br>
 * 版本： v1.0<br>
 */
public class EditImageActivity extends BaseActivity {
    @BindView(R.id.title_edit_view)
    TitleView titleEditView;
    @BindView(R.id.cropImageView)
    CropImageView cropImageView;
    @BindView(R.id.tv_whirling_view)
    TextView tvWhirlingView;
    @BindView(R.id.tv_complete_view)
    TextView tvCompleteView;

    @BindView(R.id.rl_edit_view)
    RelativeLayout rlEditView;

    private Uri uri;
    private String waterName;

    TakePictureManager takePictureManager;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_image;
    }

    @Override
    protected void initView() {
        takePictureManager = new TakePictureManager(this);

        uri = getIntent().getParcelableExtra(TakePictureManager.URI_KEY);
        waterName = getIntent().getStringExtra(TakePictureManager.WATERNAME_KEY);
        cropImageView.setImageURI(uri);

        tvWhirlingView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cropImageView.rotateImage(CropImageView.RotateDegrees.ROTATE_90D);
            }
        });

        tvCompleteView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoadingDialog();

                cropImageView.cropAsync(uri, new CropCallback() {
                    @Override
                    public void onSuccess(Bitmap cropped, Uri uri) {
                        createWaterBg(cropped,uri);


                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDilog();
                        e.printStackTrace();
                    }
                });
            }
        });
    }

    private void createWaterBg(Bitmap cropped, Uri uri) {
        Observable.create(new ObservableOnSubscribe<Pair>() {
            @Override
            public void subscribe(ObservableEmitter<Pair> e) throws Exception {
                Uri result = createWaterMark(uri);
                File file = takePictureManager.outputIamge(EditImageActivity.this, takePictureManager.decodeUriAsBitmap(result));
                Pair pair = new Pair(result,file.getPath());
                e.onNext(pair);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Pair>() {
                    @Override
                    public void accept(Pair pair) throws Exception {
                        dismissDilog();
                        Intent intent = new Intent();
                        intent.putExtra(TakePictureManager.URI_KEY,(Uri)pair.first);
                        intent.putExtra(TakePictureManager.FILEPATH_KEY,(String) pair.second);
                        setResult(Activity.RESULT_OK,intent);
                        finish();
                    }
                });
    }

    private Uri createWaterMark(Uri uri) {


        if(TextUtils.isEmpty(waterName)) {
            return uri;
        }



        Bitmap bitmap = takePictureManager.decodeUriAsBitmap(uri);

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);
        Paint p = new Paint();
        // 水印颜色
        p.setColor(Color.parseColor("#ffffff"));
        // 水印字体大小
        p.setTextSize(ScreenUtils.dip2px(EditImageActivity.this,15));
        //抗锯齿
        p.setAntiAlias(true);
        //绘制图像
        canvas.drawBitmap(bitmap, 0, 0, p);
        // 按照指定点的坐标绘制文本(在这里画了四个);water_name 不能为空
        float textWidth = p.measureText(waterName);
        int index = 0;
        canvas.rotate(-45);
        for (int positionY = bitmap.getHeight() / 5; positionY <= bitmap.getHeight(); positionY += bitmap.getHeight() / 5) {
            float fromX = - bitmap.getWidth() + (index++ % 2) * textWidth;
            for (float positionX = fromX; positionX < bitmap.getWidth(); positionX += textWidth * 2) {
                canvas.drawText(waterName, positionX, positionY, p);

            }

        }

        canvas.save();
        canvas.restore();

        final Uri result = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bmp, null,null));
        return result;
    }


}
